package com.shanghe.house.util;

import java.time.LocalDateTime;

import org.springframework.scheduling.support.CronExpression;

public class CronUtils {
    /**
     * 验证cron表达式是否有效
     */
    public static boolean isValid(String cronExpression) {
        try {
            return CronExpression.isValidExpression(cronExpression);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 判断当前时间是否符合cron表达式
     */
    public static boolean shouldExecute(String cronExpression) {
        try {
            if (!isValid(cronExpression)) {
                return false;
            }
            CronExpression cron = CronExpression.parse(cronExpression);
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime next = cron.next(now.minusMinutes(1));
            // 如果下一次执行时间在当前这一分钟内，说明应该执行
            return next != null && next.getMinute() == now.getMinute();
        } catch (Exception e) {
            return false;
        }
    }
} 